import { defineStore } from 'pinia'
import { authApi } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || 'null')
  }),
  
  getters: {
    isAdmin: (state) => state.user?.role === 'ADMIN'
  },
  
  actions: {
    async login(credentials) {
      const data = await authApi.login(credentials)
      this.token = data.token
      this.user = data.user
      localStorage.setItem('token', data.token)
      localStorage.setItem('user', JSON.stringify(data.user))
    },
    
    async register(userData) {
      await authApi.register(userData)
    },
    
    async logout() {
      try {
        await authApi.logout()
      } finally {
        this.token = ''
        this.user = null
        localStorage.removeItem('token')
        localStorage.removeItem('user')
      }
    },
    
    async fetchUserInfo() {
      const user = await authApi.getCurrentUser()
      this.user = user
      localStorage.setItem('user', JSON.stringify(user))
    }
  }
})

